package com.kylin.artwork.openapi.starter.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Collections;
import java.util.List;

/**
 * @author Damon S.
 * @version v1.0.1
 * @date 2020年05月27日 15:07
 */
@Configuration
@EnableSwagger2
public class MySwaggerConfigure {

    /** 是否开启swagger */
    @Value("${swagger.enabled:false}")
    private boolean enabled;

    @Bean
    public Docket createKylinApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(enabled)
                .useDefaultResponseMessages(false)
                .apiInfo(createApiInfo())
                .forCodeGeneration(true)
                .select()
                // 扫描所有有注解的api，用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(Collections.singletonList(
                        new ApiKey("Authorization", "Authorization", "header"))
                ).securityContexts(Collections.singletonList(
                        SecurityContext.builder()
                                .securityReferences(defaultAuth())
                                .forPaths(PathSelectors.regex("^(?!oauth).*$"))
                                .build())
                );
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope scope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = scope;
        return Collections.singletonList(new SecurityReference("Authorization", authorizationScopes));
    }


    /** 添加摘要信息 */
    private ApiInfo createApiInfo() {
        return new ApiInfoBuilder()
                .title("标题：麒麟团购_接口文档")
                .description("描述：麒麟团购接口管理")
                // 作者信息
                .contact(new Contact("songdmwork@163.com", null, null))
                .version("版本号:v1")
                .build();
    }
}
